package com.wn.activiti.service.impl;

import com.wn.activiti.service.ActivitiService;
import com.wn.common.ActivitiInstanceHistory;
import com.wn.utils.DateFormatUtil;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricActivityInstanceQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author wuqingting
 * @date 2022/10/21
 */
@Service
@Slf4j
public class ActivitiSeviceImpl implements ActivitiService {

    @Override
    public String startInstance(String processDefinitionKey, String assignee, String user) {
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        RuntimeService runtimeService = processEngine.getRuntimeService();
        //根据流程id启动流程
        HashMap<String, Object> map = new HashMap<>();
        map.put(assignee, user);//指定第一个任务负责人
        ProcessInstance instance = runtimeService.startProcessInstanceByKey(processDefinitionKey, map);

        log.debug("流程定义id:" + instance.getProcessDefinitionId());
        log.debug("流程实例id:" + instance.getId());
        log.debug("当前活动id:" + instance.getActivityId());

        return instance.getId();
    }

    @Override
    public String completeTask(String processDefinitionKey, String instanceId,String currUser, String[] nextAssignees, String[] nextUsers) {
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = defaultProcessEngine.getTaskService();
        List<Task> taskList = taskService.createTaskQuery()//获取所有任务
                .processDefinitionKey(processDefinitionKey)//流程key
                .processInstanceId(instanceId)//流程实例id
                .taskAssignee(currUser)//流程分配的人员
                .list();
        Task task=taskList.get(0);
        String taskId = task.getId();

        if (nextAssignees!=null&&nextAssignees.length!=0) {
            HashMap<String, Object> hashMap = new HashMap<>();
            for (int i=0;i<nextAssignees.length;i++) {//若下一节点有多个任务并行(如并行网关),则执行多次
                log.debug("任务id:" + taskId);
                hashMap.put(nextAssignees[i], nextUsers[i]);
            }
            taskService.setVariables(taskId, hashMap);//先指定下一结点任务审批人
        }
        taskService.complete(taskId);//根据任务id完成当前任务

        //查询当前流程实例还有没有下一个任务,如果没有,则证明流程已结束,往消息队列中发送一条消息
        List<Task> list = taskService.createTaskQuery()//获取所有任务
                .processDefinitionKey(processDefinitionKey)//流程key
                .processInstanceId(instanceId)//流程实例id
                .list();
        if (list.isEmpty()){
            //
        }


        return taskId;
    }

    @Override
    public List<ActivitiInstanceHistory> historyInfo(String instanceId) {
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        HistoryService historyService = processEngine.getHistoryService();
        // 获取 actinst表的查询对象
        HistoricActivityInstanceQuery instanceQuery =
                historyService.createHistoricActivityInstanceQuery();
        // 查询 actinst表，条件：根据 InstanceId 查询
        instanceQuery.processInstanceId(instanceId);
        // 查询 actinst表，条件：根据 DefinitionId 查询
        //instanceQuery.processDefinitionId("myEvection:1:4");
        // 增加排序操作
        instanceQuery.orderByActivityId().asc();
        // 查询所有内容
        List<HistoricActivityInstance> activityInstanceList = instanceQuery.list();
        //转为对象并保存
        List<ActivitiInstanceHistory> list = new ArrayList<>();
        for (HistoricActivityInstance instance : activityInstanceList) {
            ActivitiInstanceHistory instanceHistory = new ActivitiInstanceHistory();
            instanceHistory.setActivitiId(instance.getActivityId());
            instanceHistory.setActivitiName(instance.getActivityName());
            instanceHistory.setAssignee(instance.getAssignee());
            instanceHistory.setStartTime(DateFormatUtil.dateToString(instance.getStartTime()));
            instanceHistory.setEndTime(DateFormatUtil.dateToString(instance.getEndTime()));

            list.add(instanceHistory);
        }

        return list;
    }
}
